package server;

import java.io.File;
import java.io.FileNotFoundException;
import java.sql.Wrapper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yangpeng
 * @time 2020/4/2
 * @since 1.0.0
 * 应用容器
 */
public class Context {
    private ClassLoader webAppClassLoader;
    private Map<String,ServletWrapper> wrapperMap = new HashMap<>();

    public Map<String, ServletWrapper> getWrapperMap() {
        return wrapperMap;
    }

    public void setWrapperMap(Map<String, ServletWrapper> wrapperMap) {
        this.wrapperMap = wrapperMap;
    }

    public ClassLoader getWebAppClassLoader() {
        return webAppClassLoader;
    }

    public void setWebAppClassLoader(ClassLoader webAppClassLoader) {
        this.webAppClassLoader = webAppClassLoader;
    }

    public void loadWebApp(String appBase) throws FileNotFoundException {
        File file = new File(appBase);
        File[] files = file.listFiles();
        for (File app : files) {
            if(app.isFile()){
                continue;
            }
            initApp(app);
        }
    }

    private void initApp(File app) throws FileNotFoundException {
        String appName = app.getName();
        File file = new File(app,"web.xml");
        ServletWrapper wrapper = new ServletWrapper();
        wrapper.setWebXmlPath(file.getAbsolutePath());
        //排除server下的文件和web.xml
        //递归读取静态文件
        wrapper.loadStaticFile(app);
        //创建类加载器
        MyClassLoader classLoader = new MyClassLoader(app.getAbsolutePath()+"/server");
        wrapper.setClassLoader(classLoader);
        //读取web.xml
        wrapper.loadServlet(new File(app,"server"));
        this.wrapperMap.put(app.getName(),wrapper);
    }
}
